package com.yanq.liancar.activity;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.vondear.rxtool.view.RxToast;
import com.yanq.liancar.R;
import com.yanq.liancar.activity.base.BaseToolbarActivity;
import com.yanq.liancar.bean.BaseBean;
import com.yanq.liancar.bean.Json1Bean;
import com.yanq.liancar.bean.UserBean;
import com.yanq.liancar.url.Config;
import com.yanq.liancar.util.Utils;

import org.json.JSONArray;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class AddMailAddressActivity extends BaseToolbarActivity {
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_phoneNum)
    EditText etPhoneNum;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.et_Detailed_address)
    EditText etDetailedAddress;
    @BindView(R.id.tv_save)
    TextView tvSave;

    private int province;            //省
    private int city;                //市
    private int county;             //县
    private List<Json1Bean> jsonBeans = new ArrayList<>();
    private List<String> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private boolean isLoaded = false;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 子线程中解析省市区数据
                                initJsonData1();
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
                    isLoaded = true;
                    break;
                case MSG_LOAD_FAILED:
                    break;
            }
        }
    };
    private String where,token;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Utils.setStatusBar(this, true,false);
        setContentView(R.layout.activity_addmailaddress);
        ButterKnife.bind(this);
        where=getIntent().getExtras().getString("where");
        if ("MineFragment".equals(where)){
            token=UserBean.getcToken(this);
        }else {
            token=UserBean.getbToken(this);
        }
        handler.sendEmptyMessage(MSG_LOAD_DATA);
        mTvTitle.setText("添加邮寄地址");
    }

    @OnClick({R.id.tv_address, R.id.tv_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_address:
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                // 隐藏软键盘
                imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
                if (isLoaded) {
                    showPickerView();
                } else {
                    Toast.makeText(this, "城市数据初始化中...", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.tv_save:
                addAddress();
                tvSave.setEnabled(true);
                break;
        }
    }

    private void addAddress(){
        if (isNull()){
            OkGo.<String>post(Config.s + "llc/api/insertpost")
                    .tag(this)
                    .params("token", token)
                    .params("gainpeo", etName.getText().toString().trim())
                    .params("gainaddress", tvAddress.getText().toString().trim())
                    .params("cont_phone", etPhoneNum.getText().toString().trim())
                    .params("addr_detail", etDetailedAddress.getText().toString().trim())
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(Response<String> response) {
                            Gson gson = new Gson();
                            BaseBean baseBean=gson.fromJson(response.body(),BaseBean.class);
                            if (baseBean.isIsSuccess()){
                                RxToast.success(baseBean.getOutputMessage());
                                tvSave.setEnabled(false);
                                finish();
                            }else {
                                RxToast.error(baseBean.getOutputMessage());
                            }

                        }

                        @Override
                        public void onError(Response<String> response) {
                            super.onError(response);
                            RxToast.error("服务器连接错误");
                        }
                    });
        }
    }


    private boolean isNull() {
        if (TextUtils.isEmpty(etName.getText().toString().trim())) {
            RxToast.error("请填写收货人");
            return false;
        }
        if (TextUtils.isEmpty(etPhoneNum.getText().toString().trim())) {
            RxToast.error("请填写联系电话");
            return false;
        }
        if (TextUtils.isEmpty(tvAddress.getText().toString().trim())) {
            RxToast.error("请选择地址");
            return false;
        }
        if (TextUtils.isEmpty(etDetailedAddress.getText().toString().trim())) {
            RxToast.error("请输入详细地址");
            return false;
        }
        return true;
    }
    private void showPickerView() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = jsonBeans.get(options1).getPickerViewText() +
                        options2Items.get(options1).get(options2) +
                        options3Items.get(options1).get(options2).get(options3);
                province=jsonBeans.get(options1).getArea_id();
                city=jsonBeans.get(options1).getChild().get(options2).getArea_id();
                county=jsonBeans.get(options1).getChild().get(options2).getChild().get(options3).getArea_id();
                //Toast.makeText(AddMyLocationActivity.this, tx, Toast.LENGTH_SHORT).show();
                tvAddress.setText(tx);

            }
        })

                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }
    private void initJsonData1() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = getJson(this, "json.json");//获取assets目录下的json文件数据

        ArrayList<Json1Bean> jsonBean = parseData1(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        jsonBeans = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> provilist=new ArrayList<>();
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）
            provilist.add(jsonBean.get(i).getArea_name());

            for (int c = 0; c < jsonBean.get(i).getChild().size(); c++) {//遍历该省份的所有城市
//                String CityName = ;
                CityList.add(jsonBean.get(i).getChild().get(c).getArea_name());//添加城市
                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getChild().get(c).getChild() == null
                        || jsonBean.get(i).getChild().get(c).getChild().size() == 0) {
                    City_AreaList.add("");
                } else {
                    for (int j = 0; j < jsonBean.get(i).getChild().get(c).getChild().size(); j++) {
                        City_AreaList.add(jsonBean.get(i).getChild().get(c).getChild().get(j).getArea_name());
                    }

                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }
            options1Items.addAll(provilist);
            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        handler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }
    public String getJson(Context context, String fileName) {

        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = context.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    public ArrayList<Json1Bean> parseData1(String result) {//Gson 解析
        ArrayList<Json1Bean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                Json1Bean entity = gson.fromJson(data.optJSONObject(i).toString(), Json1Bean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            handler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
    }
}
